package com.example.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.usercenter.common.ResultUtils;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.service.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class PreCacheJob {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    //重点用户
    private List<Long> mainUserList = Arrays.asList(1L);
    @Scheduled(cron = "0 0 21 * * ?")
    public void doCacheRecommendUser(){
        RLock lock = redissonClient.getLock("yupaopao:precache:job:docache:lock");
        try {
            if (lock.tryLock(0,30000L,TimeUnit.MILLISECONDS)){
                for (Long userId : mainUserList) {
                    QueryWrapper query = new QueryWrapper();
                    Page<User> page = userService.page(new Page<>(1, 20), query);
                    String redisKey = String.format("yupaopao:user:recommend:%s",userId);
                    ValueOperations operations = redisTemplate.opsForValue();
                    try {
                        operations.set(redisKey,operations,30000,TimeUnit.MILLISECONDS);
                    }catch (Exception e){

                    }
                }
            }
        }catch (Exception e){

        }finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }
}
